/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.message.impl;


import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.transaction.annotation.MyTransactionListener;
import com.lvyh.lightframe.transaction.common.config.TransactionApplicationConfig;
import com.lvyh.lightframe.transaction.common.config.message.KafkaMessageConfig;
import com.lvyh.lightframe.transaction.common.constant.TransactionConstant;
import com.lvyh.lightframe.transaction.common.domain.Participant;
import com.lvyh.lightframe.transaction.core.ext.Spi;
import com.lvyh.lightframe.transaction.core.message.TransactionMessage;
import com.lvyh.lightframe.transaction.core.serialize.Serializer;
import com.lvyh.lightframe.transaction.core.service.TransactionInvocationService;
import com.lvyh.lightframe.transaction.core.task.ConsumeMessageTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Kafka message queuing support
 */
@Spi("kafkamessage")
@Slf4j
public class KafkaTransactionMessage implements TransactionMessage {

    private Serializer serializer;

    private TransactionInvocationService transactionInvocationService;

    private KafkaProducer<String, Participant> producer = null;

    private KafkaConsumer<String, Participant> consumer = null;

    private ExecutorService executorService = Executors.newCachedThreadPool();

    @Override
    public void init(TransactionApplicationConfig transactionApplicationConfig) {
        KafkaMessageConfig messageConfig = (KafkaMessageConfig) transactionApplicationConfig.getMessageConfig();
        producer = this.buildProducer(messageConfig);
        consumer = this.buildConsumer(messageConfig);
    }

    private KafkaProducer<String, Participant> buildProducer(KafkaMessageConfig messageConfig) {
        Properties props = new Properties();
        props.put("bootstrap.servers", messageConfig.getUrl());
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        //props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "com.lvyh.lightframe.transaction.core.kafka.CustomKafkaSerializer");
        KafkaProducer<String, Participant> producer = new KafkaProducer<String, Participant>(props);
        return producer;
    }

    private KafkaConsumer<String, Participant> buildConsumer(KafkaMessageConfig messageConfig) {
        Properties props = new Properties();
        props.put("bootstrap.servers", messageConfig.getUrl());
        // Specifies the ID of the consumer group
        props.put("group.id", messageConfig.getGroupId());
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        //props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "com.lvyh.lightframe.transaction.core.kafka.CustomKafkaDeserializer");

        KafkaConsumer<String, Participant> consumer = new KafkaConsumer<String, Participant>(props);
        return consumer;
    }

    @Override
    public void setObjectSerializer(Serializer serializer) {
        this.serializer = serializer;
    }

    @Override
    public void setInvocationService(TransactionInvocationService transactionInvocationService) {
        this.transactionInvocationService = transactionInvocationService;
    }

    @Override
    public void send(Participant participant) {
        String topicName = participant.getDestination();
        ProducerRecord<String, Participant> record = new ProducerRecord<>(topicName, participant);
        //Asynchronous send
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception == null) {
                    // Message sent successfully
                    log.info("Message sent successfully, topic:{}, message offset:{}", topicName, metadata.offset());
                }
            }
        });
        log.info("Message send complete, topic:{}, value:{}", topicName, JSON.toJSONString(participant));
    }

    @Override
    public String getMessageQueueName() {
        return TransactionConstant.TRANSACTION_MESSAGE_KAFKA;
    }

    @Override
    public void listen(List<MyTransactionListener> listeners) {
        for (MyTransactionListener listener : listeners) {
            String topicName = listener.destination();
            executorService.execute(new ConsumeMessageTask(consumer, transactionInvocationService, topicName));
        }
    }
}
